package com.example.sjh_web

import android.content.Intent
import android.os.Bundle
import android.os.Looper
import android.view.MenuItem
import android.view.View
import android.view.View.OnCreateContextMenuListener
import android.widget.AdapterView
import android.widget.AdapterView.AdapterContextMenuInfo
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.example.sjh_web.other.sjh_favoritesAdapter
import com.example.sjh_web.other.sjh_favoritesItem
import kotlinx.android.synthetic.main.sjh_favorites_activity.*
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import kotlin.concurrent.thread


class sjh_FavoritesActivity : AppCompatActivity() {
    private var favoritesList = ArrayList<sjh_favoritesItem>()
    var adapter : sjh_favoritesAdapter? = null
    private var map: ArrayList<sjh_favoritesItem> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.sjh_favorites_activity)
        adapter = sjh_favoritesAdapter(this, R.layout.sjh_favorites_item, favoritesList)
        initFvaorites()

        //左上角图标点击弹出选项
        operate.setOnClickListener {
            operated.visibility = View.VISIBLE
            adapter!!.setflag(true)
            adapter!!.notifyDataSetChanged()
        }

        //点击“取消”退出操作
        cancel.setOnClickListener {
            operated.visibility = View.GONE
            adapter!!.setflag(false)
            for ( i in favoritesList ){
                if (map.contains(i)){
                    map.remove(i)
                    i.check = false
                }
            }
            number.text = countNumber().toString()
            adapter!!.notifyDataSetChanged()
        }

        //全选
        all_selseted.setOnClickListener {
            reversed.isChecked = false
            if (all_selseted.isChecked) {
                for (i in favoritesList) {
                    if(!map.contains(i)){
                        map.add(i)
                        i.check = true
                    }
                }
            } else {
                for (i in favoritesList) {
                    if(map.contains(i)){
                        map.remove(i)
                        i.check = false
                    }
                }
            }
            number.text = countNumber().toString()
            adapter!!.notifyDataSetChanged()
        }

        //反选
        reversed.setOnClickListener {
            all_selseted.isChecked = false
            for (i in favoritesList) {
                if (map.contains(i)) {
                    map.remove(i)
                    i.check = false
                } else {
                    map.add(i)
                    i.check = true
                }
            }
            number.text = countNumber().toString()
            adapter!!.notifyDataSetChanged()
        }

        //删除
        delete.setOnClickListener {
            if (countNumber()!=0) {
                AlertDialog.Builder(this).apply {
                    setTitle("提示")
                    setMessage("确认删除吗？")
                    setCancelable(false)
                    setPositiveButton("确认") { dialog, which ->
                        for (i in map) {
                            delete_oneFavorite(i.id)
                            favoritesList.remove(i)
                        }
                        all_selseted.isChecked = false
                        reversed.isChecked = false
                        map.clear()
                        number.text = countNumber().toString()
                        adapter!!.notifyDataSetChanged()
                    }
                    setNegativeButton("取消") { dialog, which ->
                    }
                    show()
                }
            }else{
                Toast.makeText(this,"没有选中至少一项", Toast.LENGTH_SHORT).show()
            }
        }

        //单选、多选
        listView.setOnItemClickListener(AdapterView.OnItemClickListener { parent, view, position, id ->
            if (adapter!!.flag) {    //如果进入操作模式，则不进行页面跳转
                val holder: sjh_favoritesAdapter.ViewHolder = view.tag as sjh_favoritesAdapter.ViewHolder
                //改变CheckBox状态
                holder.favorites_check.isChecked = !holder.favorites_check.isChecked
                if (holder.favorites_check.isChecked) {
                    map.add(favoritesList[position])
                    favoritesList[position].check = true
                } else {
                    map.remove(favoritesList[position])
                    favoritesList[position].check = false
                }
                number.text = countNumber().toString()
            } else {
                val favorites_item = favoritesList[position]
                val intent = Intent()
                intent.putExtra("url", favorites_item.url)
                setResult(RESULT_OK, intent)
                finish()
            }
        })

        //删除方法1：长按删除，不弹出菜单
//        listView.setOnItemLongClickListener(AdapterView.OnItemLongClickListener { parent, view, position, id ->
//            try {
//                val favorites_item = favoritesList[position]
////                val listView: ListView = parent as ListView
////                val favoritesItem: sjh_favoritesItem = listView.getItemAtPosition(position) as sjh_favoritesItem
//                val favoritesAdapter = listView.adapter as sjh_favoritesAdapter
//                favoritesAdapter.remove(favorites_item)
//                delete_oneFavorite(favorites_item.id)
//                favoritesAdapter.notifyDataSetChanged()
//                listView.invalidate()
//            } catch (e: java.lang.Exception) {
//                return@OnItemLongClickListener false
//            }
//            true
//        })


        //删除方法2：长按弹出菜单选项
        listView.setOnCreateContextMenuListener(OnCreateContextMenuListener { menu, v, menuInfo ->
            menu.add(0, 0, 0, "删除此项")
        })
    }

    //对弹出菜单进行对应的操作
    override fun onContextItemSelected(item: MenuItem): Boolean {
        val info = item.getMenuInfo() as AdapterContextMenuInfo
        //info.id得到listview中选择的条目绑定的id
        val id = info.id.toString()
        return when (item.getItemId()) {
            0 -> {
                val favorites_item = favoritesList[Integer.parseInt(id)]
                val favoritesAdapter = listView.adapter as sjh_favoritesAdapter
                favoritesAdapter.remove(favorites_item)
                delete_oneFavorite(favorites_item.id)
                favoritesAdapter.notifyDataSetChanged()
                listView.invalidate()
                true
            }
            else -> super.onContextItemSelected(item)
        }
    }


    fun countNumber(): Int {
        var number = 0
        for(i in favoritesList){
            if(i.check){
                number++
            }
        }
        return number
    }

    private fun initFvaorites() {
        thread {
            try {
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("http://192.168.43.227:8888/query").build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                if (responseData != null) {
                    parseJSONWithJSONObject(responseData)
                }
                showResponse(favoritesList)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    //展示listview
    private fun showResponse(favoritesList: ArrayList<sjh_favoritesItem>) {
        runOnUiThread {
            adapter = sjh_favoritesAdapter(this, R.layout.sjh_favorites_item, favoritesList)
            listView.adapter = adapter
        }
    }

    //从JSON格式中取值
    private fun parseJSONWithJSONObject(jsonData: String) {
        try {
            val jsonArray = JSONArray(jsonData)
            for( i in 0 until jsonArray.length()) {
                val jsonObject = jsonArray.getJSONObject(i)
                val id = jsonObject.getString("id")
                val url = jsonObject.getString("url")
                val title = jsonObject.getString("title")
                favoritesList.add(sjh_favoritesItem(id, url, title,false))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //删除收藏夹中的一条记录
    private fun delete_oneFavorite(id: String) {
        thread {
            try {
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("http://192.168.43.227:8888/delete?id=$id")
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                if (responseData != null){
                    Looper.prepare();
                    Toast.makeText(this, responseData, Toast.LENGTH_SHORT).show()
                    Looper.loop();
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}